package com.ug_project.Async

import android.os.Handler
import android.os.Message

/**
 * Created by yeganaaa on 2017/2/25.
 */
/**
 * يىڭى لىنيەدە ئىجرا قىلىدۇ
 */
//fun runASync(delay_MS: Long = 0, action: () -> Unit)
//{
//    Thread(Runnable {
//        Thread.sleep(delay_MS)
//        action()
//    }).start()
//}

/**
 * كۆرۈنمە يۈزنىڭ ئۈستىدە يىڭىدىن بىر لىنيە ئىجرا قىلىدۇ
 * yeganaaa 2017/02/27 GMT+6.0 04:37
 */
class runASyncOnUIThread{

    private var _action: (() -> Unit)? = null
    private val RUN = 1

    private var handler = object : Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when(msg?.what)
            {
                RUN -> {
                    _action?.invoke()
                    this.removeMessages(RUN)
                }
            }
        }
    }
    /**
     *كۆرۈنمە يۈز ئاساسى لىنيەسىدە ئىجرا قىلىدۇ
     */
    fun runUI(action: (() -> Unit)? = null)
    {
        _action = action
        val message = Message()
        message.what = RUN
        handler.sendMessage(message)
    }

    fun delay(Milli_Second: Long)
    {
        Thread.sleep(Milli_Second)
    }
}

/**
 * يىڭى لىنيە قۇرۇش
 * yeganaaa 2017/02/27 GMT+6.0 04:37
 */
fun runASync(delay_MS: Long = 0, threadCount: Int = 1, constractor: runASyncOnUIThread.(threadID: Int) -> Unit)
{
    repeat(threadCount)
    {
        val uithread = runASyncOnUIThread()
        var runnable = Runnable {
            Thread.sleep(delay_MS)
            uithread.constractor(it)
        }

        Thread(runnable).start()
    }
}